<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\RefundRow;
use App\Admin\Extensions\Tools\UserGender;
use App\Http\Controllers\Admin\Business\Repository\Combo;
use App\Http\Controllers\Admin\Business\Repository\ComboOrder;
use App\Member;
use App\PayOrder;

use App\Repositories\OrderRepository;
use App\User;
use Encore\Admin\Auth\Permission;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Table;

class OrderController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('已支付订单');
            $content->description('已支付订单');
            $content->body($this->grid());
        });
    }
    public function total(Request $request){
        if($request->searchTime){
            $time=explode('~',$request->searchTime);
            $start_time=$time[0];
            $end_time=$time[1];
        }else{
            $start_time='';
            $end_time='';
        }

        return Admin::content(function (Content $content)use($start_time,$end_time) {
            $content->header('营业汇总报表');
            $content->description('营业汇总报表');
            $combo= \App\Http\Controllers\Admin\Business\Repository\Combo::where('is_bind',1)->select('id','title','zhilv_price')->get();
            //总数量
           $total= \DB::table('pay_orders')
                ->join('combo_orders','combo_orders.outTradeNo','=','pay_orders.out_trade_no')
                ->select('combo_orders.combo_id',\DB::raw('sum(combo_orders.total_num) as total'),DB::raw('sum(combo_orders.total_num*combo_orders.zhilv_price) as zhilv'))
                ->groupBy('combo_orders.combo_id')
                ->where('pay_orders.is_pay','=',1);
           if($start_time!=''){
            $total=$total->where('pay_orders.created_at','>',$start_time)
                   ->where('pay_orders.created_at','<',$end_time);
           }
           $total=$total->get()->keyBy('combo_id')->all();

           //ticket
            $sendTicket= \DB::table('pay_orders')
                ->join('combo_orders','combo_orders.outTradeNo','=','pay_orders.out_trade_no')
                ->select('combo_orders.combo_id',\DB::raw('sum(combo_orders.total_num) as total'),DB::raw('sum(combo_orders.total_num*combo_orders.zhilv_price) as zhilv'))
                ->groupBy('combo_orders.combo_id')
                ->where('pay_orders.is_pay','=',1)
                ->where('combo_orders.is_send',1);
            if($start_time!=''){
                $sendTicket=$sendTicket->where('pay_orders.created_at','>',$start_time)
                ->where('pay_orders.created_at','<',$end_time);
            }

            $sendTicket=$sendTicket->get()->keyBy('combo_id')->all();
            //退票
            $refundTicket= \DB::table('pay_orders')
                ->join('combo_orders','combo_orders.outTradeNo','=','pay_orders.out_trade_no')
                ->select('combo_orders.combo_id',\DB::raw('sum(combo_orders.total_num) as total'),DB::raw('sum(combo_orders.total_num*combo_orders.zhilv_price) as zhilv'))
                ->groupBy('combo_orders.combo_id')
                ->where('pay_orders.is_pay','=',1)
                ->where('combo_orders.is_refund',1);
            if($start_time!=''){
                $refundTicket=$refundTicket->where('pay_orders.created_at','>',$start_time)
                    ->where('pay_orders.created_at','<',$end_time);
            }
            $refundTicket=$refundTicket->get()->keyBy('combo_id')->all();
            $content->row(view('administrator.order.total',compact('combo','sendTicket','refundTicket','total')));
        });
    }
    protected function froms(){
        $form= new \Encore\Admin\Widgets\Form();
        $form->action('');

        $form->method('GET');
        $form->dateRange('created_at', 'updated_at');
        return $form->render();
}
    protected function table(){

// table 1
        $headers = ['Id', 'Email', 'Name', 'Company'];
        $rows = [
            [1, 'labore21@yahoo.com', 'Ms. Clotilde Gibson', 'Goodwin-Watsica'],
            [2, 'omnis.in@hotmail.com', 'Allie Kuhic', 'Murphy, Koepp and Morar'],
            [3, 'quia65@hotmail.com', 'Prof. Drew Heller', 'Kihn LLC'],
            [4, 'xet@yahoo.com', 'William Koss', 'Becker-Raynor'],
            [5, 'ipsa.aut@gmail.com', 'Ms. Antonietta Kozey Jr.'],
        ];

        $table = new Table($headers, $rows);
        $html=" <div class=\"box-body\">";

        $html.= $table->render();
        $html.="</div>";
        return $html;
    }
    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }
    public function detail(ComboOrder $comboOrder){
     
        $payOrder= PayOrder::where('out_trade_no',$comboOrder->outTradeNo)->first();
        return Admin::content(function (Content $content) use ($comboOrder,$payOrder) {
            $content->header('查看订单');
            // body 方法可以接受 Laravel 的视图作为参数
            $content->body( view('administrator.order.show',compact('comboOrder','payOrder')));
        });

    }
    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()

    {
        return Admin::grid(ComboOrder::class, function (Grid $grid) {
            $grid->model()->with('combo')
                ->join('pay_orders', 'pay_orders.out_trade_no', '=', 'combo_orders.outTradeNo')
                ->join('members', 'members.id', '=', 'combo_orders.member_id')
                ->where('pay_orders.is_pay', 1)
                ->select('pay_orders.body','combo_orders.id',
                'combo_orders.rate',    'pay_orders.out_trade_no','combo_orders.total_num','combo_orders.activity_id','combo_orders.is_send','members.nickname','members.mobile','members.id_number','members.truename','combo_orders.combo_price','combo_orders.created_at as pay_time','combo_orders.price','combo_orders.is_refund','combo_orders.zhilv_price','members.pid','combo_orders.combo_id','combo_orders.send_time')
                ->orderBy('combo_orders.is_send','desc')
                ->orderBy('combo_orders.send_time','desc')
            ;
            $grid->id('ID')->sortable();
            $grid->body('套餐名称');
            $grid->price('订单价格');
            $grid->out_trade_no('订单号');
            $grid->pay_time('订单购买时间')->sortable();
            $grid->id_number('身份证号');
            $grid->truename('真实姓名');
            $grid->total_num('购买数量');
            $grid->activity_id('是否参与活动')->display(function($value){
                if($value){
                    return $value;
                }else{
                    return '尚未参加活动';
                }
            });
            $grid->is_send('门票')->display(
                function ($value){
                    return $value==1 ? '已发放' :'未发放';
                }
            );
            $grid->send_time('门票发放时间')->display(
                function($value){
                    return $value ?? '尚无记录';
                }
            )->sortable();
            $grid->nickname('用户昵称');
            $grid->mobile('用户手机号');
            $grid->pid('推广人')->display(
                function($value){

                    if($value){
                       $user= Member::find($value);
                       if ($user)
                       return "id:".$user->id."\n昵称:".$user->nickname;
                    }else{
                        return '无推广人';
                    }
                }
            );
            $grid->column('rate','订单推广提成')->display(
                function($value){
                    return round($this->price*$value/100,2);
                });
            $grid->zhilv_price('智旅定价')->display(function($value){
               return  $this->total_num*$value;
            });
            $grid->is_refund('是否退票')->display(function($value){
                return $value==1 ? '已退票' : '未退票';
            });
            $grid->disableCreateButton();

            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->append("<a class='btn btn-xs btn-success' href='/administrator/order/{$actions->getKey()}'>查看</a>");
            });
            $grid->tools(function ($tools) {
                //验票功能

                $tools->append(new UserGender());
                //禁用批量删除
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });

            });

            $grid->filter(function($filter){
                $filter->disableIdFilter();
                $filter->like('nickname','用户昵称');
                $filter->equal('outTradeNo','订单号');
                $filter->equal('is_send','门票发放')->select(['0' => '未发放','1'=>'已发放']);
                $filter->between('send_time', '发放时间')->datetime();
                $filter->equal('is_refund','是否退票')->select(['0' => '未退票','1'=>'已退票']);
               // $filter->between('combo_orders.created_at', '支付时间')->datetime();

            });

        });
    }
   public function inspectTicket($out_trade_no){
       Permission::check('inspectTicket');
       $comboOrder= ComboOrder::with('combo','member')->where('outTradeNo',$out_trade_no)->first();
       if(!$comboOrder){
           return Response()->json(
               [
                   'code'=>'error',
                   'message'=>'订单不存在,请检查订单号',
               ]
           );
       }
       //检查是否发票
       if($comboOrder->is_send){
           return Response()->json(
               [
                   'code'=>'error',
                   'message'=>'门票已发放',
                    'data'=>$comboOrder->toArray()
               ]
           );
       }
       //检查门票是否退票
       if($comboOrder->is_refund){
           return Response()->json(
               [
                   'code'=>'error',
                   'message'=>'门票已退票',
                   'data'=>$comboOrder->toArray()
               ]
           );
       }
       //
       return Response()->json(
           [
               'code'=>'success',
               'message'=>'门票查询成功',
               'data'=>$comboOrder->toArray()
           ]
       );


   }
   public function sendTicket($comboOrderId){
       $comboOrder= ComboOrder::with('member')->where('id',$comboOrderId)->first();
       if(!$comboOrder){
           return Response()->json(
               [
                   'code'=>'error',
                   'message'=>'订单不存在,请检查订单号',
               ]
           );
       }
       //检查是否发票
       if($comboOrder->is_send){
           return Response()->json(
               [
                   'code'=>'error',
                   'message'=>'门票已发放',
                   'data'=>$comboOrder->toArray()
               ]
           );
       }
       //检查门票是否退票
       if($comboOrder->is_refund){
           return Response()->json(
               [
                   'code'=>'error',
                   'message'=>'门票已退票',
                   'data'=>$comboOrder->toArray()
               ]
           );
       }
       $comboOrder->is_send=1;
       $comboOrder->send_time=Carbon::now();
       $comboOrder->save();
       return Response()->json(
           [
               'code'=>'success',
               'message'=>'门票发放成功',
               'data'=>PayOrder::where('out_trade_no',$comboOrder->outTradeNo)->first()->body
           ]
       );
   }

    //退款
    public function refund(ComboOrder $comboOrder,Request $request,OrderRepository $orderRepository){

        $is_refund=$request->distribute=='on' ? 1 : false;

        $orderRepository->refundOrder($comboOrder,$is_refund);
        $success=new MessageBag([
            'title'=>'退款成功',
            'message'=>'退款成功',

        ]);


        return redirect()->back()->with(compact('success'));
    }
    /**
     * Make a form builder.
     * @return Form
     */
    protected function form()
    {
        return Admin::form(PayOrder::class, function (Form $form) {
            $form->display('id', 'ID');
            $form->display('created_at', 'Created At');
            $form->display('updated_at', 'Updated At');
        });
    }
}
